<template>
  <div class="settings-page">
    <el-card class="center-card">
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="auto"
          @validate="onValidate"
      >
        <el-form-item label="">
          <el-text class="welcome-title" size="large">注册观弈零代码平台</el-text>
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input :disabled="!agreed" v-model="form.phoneNumber" prefix-icon="el-icon-mobile-phone"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input :disabled="!agreed" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox @change="handleCheckChange">我已阅读并同意服务协议和隐私政策</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              :plain="!agreed"
              @click="submitForm"
          >下一步</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElForm, ElFormItem, ElInput, ElCheckbox, ElButton, ElText, ElCard,ElMessage } from 'element-plus';
import { registerInfoKey } from "@/config/app.keys";
import {checkPhoneUnique} from "@/api/login"

interface Form {
  phoneNumber: string;
  name: string;
}

const form = ref<Form>({
  phoneNumber: '',
  name: ''
});
const agreed = ref(false);
const formRef = ref<InstanceType<typeof ElForm>>();
const router = useRouter();
const registerInfo = ref(JSON.parse(localStorage.getItem(registerInfoKey)))

const rules = {
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
    { pattern: /^1[3-9]\d{9}$/, message: '请正确填写手机号', trigger: ['blur', 'change'] }
  ],
  name: [{ required: true, message: '请输入姓名', trigger: ['blur', 'change'] }]
};

const submitForm = () => {
  if (!formRef.value) {
    console.error('Form reference is undefined.');
    return;
  }
  formRef.value.validate(async (valid) => {
    if (valid) {
      //检查手机号是否已注册
      let res;
      res = await checkPhoneUnique(form.value.phoneNumber)
      if (res.data) {
        registerInfo.value.userInfo.username = form.value.name;
        registerInfo.value.userInfo.phone = form.value.phoneNumber;
        localStorage.setItem(registerInfoKey, JSON.stringify(registerInfo.value));
        router.push('/sendmsgverifycode');
      } else {
        ElMessage.error('手机号已注册!');
      }
    }else{

      ElMessage.error('表单数据无效，请检查填写的信息');
    }
  });
};

const onValidate = (valid: boolean) => {
  // 更新按钮的状态以禁用未完成的表单
  // 注意：submitButton 应该是一个有效的引用或者变量
  // submitButton.plain = !valid;
};

const handleCheckChange = (val: boolean) => {
  agreed.value = val;
};

watch(agreed, (newVal) => {
  // 禁用/启用表单元素
  for (const key in form.value) {
    form.value[key] = newVal ? form.value[key] : '';
  }
});

onMounted(() => {
  // 初始化表单值，例如填充默认值或从存储中恢复状态
});
</script>

<style scoped>
.settings-page {
  margin: auto;
  display: flex;
  justify-content: center;
  height: 80vh;
}
.el-form .el-form-item__content {
  display: flex;
  align-items: center;
  gap: 8px;
}
.welcome-title {
  margin-top: 10px;
  margin-bottom: 10px;
  font-size: 22px;
  font-weight: 600;
  line-height: 30px;
  color: #1f2329;
}
.center-card {
  width: 500px;
}
</style>
